﻿using System;
using UnityEngine;

namespace EchoFramework
{
    /// <summary>
    /// 基于MonoBehaviour的单例抽象类
    /// </summary>
    public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>
    {
        private static T instance;

        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    GameObject go = GameObject.Find(typeof(T).Name);
                    if (null == go)
                    {
                        go = new GameObject(typeof(T).Name);
                    }

                    instance = go.GetComponent<T>();

                    if (null == instance)
                    {
                        instance = go.AddComponent<T>();
                    }
                }

                return instance;
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public virtual void OnInit()
        {
            GameLogger.LogFormat("{0}初始化...", typeof(T).Name);
        }


        /// <summary>
        /// 每帧更新
        /// </summary>
        public virtual void OnUpdate()
        {
        }

        /// <summary>
        /// 关闭
        /// </summary>
        public virtual void OnClose()
        {
        }
    }
}